package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.common.Code;
import com.xxx.common.Result;
import com.xxx.pojo.User;
import com.xxx.service.UserService;
import com.xxx.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserService userService;


    @GetMapping("/login")
    public Result login(String phone, String code){
        log.info("手机号：{}   验证码：{}",phone,code);
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        String currentCode = (String) ops.get(phone);
        if (currentCode == null || !currentCode.equals(code)){
            return new Result(null, Code.GET_ERR,"验证码错误！！！");
        }

        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone,phone));

        redisTemplate.delete(phone);

        if (one == null){
            User user = new User();
            user.setPhone(phone);
            boolean save = userService.save(user);
            log.info("user:{}",user);
            String token = JWTUtil.createToken(user.getId().toString());
            ops.set(user.getId().toString(),user);
            return save ? new Result(token,Code.GET_OK) : new Result(null,Code.GET_ERR,"发生错误，请稍后再试");
        }

        String token = JWTUtil.createToken(one.getId().toString());
        ops.set(one.getId().toString(),one);
        log.info("token:{}",token);
        return new Result(token,Code.GET_OK);
    }

    @GetMapping("/getCode")
    public void getCode(String phone){
        String s = "0123456789";
        String code = "";
        for (int i = 0; i < 4; i++) {
            Random random = new Random();
            int index = random.nextInt(s.length());
            code = code + s.charAt(index);
        }

        log.info("验证码code：{}",code);

        ValueOperations<String, Object> ops = redisTemplate.opsForValue();

        ops.set(phone,code,5*60, TimeUnit.SECONDS);

    }

}
